package com.quickcode.example.juc;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 串行化
 */
public class CompletableFutureExample2 {

    public static final ExecutorService EXECUTORSERVICE = Executors.newCachedThreadPool();

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            /*串行执行，第一步*/
            @Override
            public Integer get() {
                return 10;
            }
        }, EXECUTORSERVICE).thenApplyAsync(new Function<Integer, Integer>() {
            /*串行执行，第二步*/
            @Override
            public Integer apply(Integer integer) {
                System.out.println("==integer==" + integer);
                return integer / 0;
            }
        }, EXECUTORSERVICE).handle(new BiFunction<Integer, Throwable, Integer>() {
            /*执行时发生异常则进行异常处理并返回一个修正值*/
            @Override
            public Integer apply(Integer integer, Throwable throwable) {
                System.out.println("integer:" + integer);
                System.out.println("Throwable:" + throwable);
                return 5;
            }
        }).thenApply(new Function<Integer, Integer>() {
            /*后面再串任务*/
            @Override
            public Integer apply(Integer integer) {
                return integer * integer;
            }
        });

        Integer sout = future.get();
        System.out.println("sout:" + sout);
    }
}